package com.mysterymall.Controller;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.io.Resource;
import org.springframework.core.io.UrlResource;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;

import java.net.MalformedURLException;
import java.nio.file.Path;
import java.nio.file.Paths;

@Controller
@RequestMapping("/videos")
public class VideoController {

    @Value("${mystery.rootPath}")
    private String rootPath;

    @GetMapping
    public ResponseEntity<Resource> streamVideo(@RequestParam String videoName) {
        try {
            // 构建视频文件的路径
            Path videoPath = Paths.get(rootPath).resolve(videoName);
            Resource videoResource = new UrlResource(videoPath.toUri());

            // 设置响应头，使浏览器能够正确处理视频
            HttpHeaders headers = new HttpHeaders();
            headers.setContentType(MediaType.valueOf("video/mp4"));

            // 返回资源
            return ResponseEntity.ok()
                    .headers(headers)
                    .body(videoResource);
        } catch (MalformedURLException e) {
            e.printStackTrace();
            return ResponseEntity.notFound().build();
        }
    }
}